﻿using Handy_DNS.Load;
using Handy_DNS.View;
using HandyControl.Controls;
using Kxx_Common.Memory;
using Kxx_Task.DNS;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;

namespace Handy_DNS
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        // 找到窗体
        //  FindWindowW F1 在MSDN Doc中查找
        //  HWND FindWindowW(
        //  LPCWSTR lpClassName,
        //  LPCWSTR lpWindowName
        //);
        [DllImport("User32", CharSet = CharSet.Unicode)]
        static extern IntPtr FindWindowW(string lpClassName, string lpWindowName);

        // 显示到前台
        // SetForegroundWindow F1 在MSDN Doc中查找
        // BOOL SetForegroundWindow(
        // HWND hWnd
        // );
        [DllImport("User32", CharSet = CharSet.Unicode)]
        static extern Boolean SetForegroundWindow(IntPtr hWnd);

        System.Threading.Mutex mutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            #region 互斥单例运行
            mutex = new System.Threading.Mutex(true, "kexiaoxiao-dns");
            if (mutex.WaitOne(0, false))
            {
                base.OnStartup(e);
            }
            else
            {
                // 查找窗体、显示到前台
                IntPtr intPtr = FindWindowW(null, "kexiaoxiao-dns");
                if (intPtr != IntPtr.Zero)
                {
                    SetForegroundWindow(intPtr);
                }// 退出
                this.Shutdown();
            } 
            #endregion

            #region 内存回收
            LierdaCracker cracker = new LierdaCracker();
            cracker.Cracker();
            #endregion

            #region 初始加载
            DNSLoad.Init(false);
            LogSocket.Init();
            #endregion

            #region 主程序
            new MainWindow().ShowDialog(); 
            #endregion

            #region 程序结束
            Application.Current.Shutdown();
            #endregion
        }
    }
}
